import Taro, { Events } from '@tarojs/taro';
import request from './request'
import {PostData, FileData } from 'taro-axios'
import moment from 'moment';
export const toast = {
    show(title, icon = 'none'){
        let obj = {title, mask: true, icon};
        if(icon === 'success' || icon === 'error' || icon === 'none'){
            Object.assign(obj, {
                duration: 2000
            })
        }
        Taro.showToast(obj)
    },
    hide(){
        Taro.hideToast();
    },
    //弹窗
    modal(options = {}){
        return new Promise((resolve, reject) => {
            Taro.showModal(Object.assign({
                title: '提示',
                confirmColor: '#5677fd',
                confirmText: '确认',
                cancelColor: '#606266',
                cancelText: '取消',
                content: '确认删除？',
                showCancel: true,
                success({cancel, confirm, errMsg}){
                    if(cancel){
                        reject(errMsg)
                    }else if(confirm){
                        resolve(errMsg)
                    }
                },
                fail: reject
            }, options))
        })
    },
    //显示操作菜单
    actionSheet(itemList = [], itemColor = '#222222'){
        return new Promise((resolve, reject) => {
            Taro.showActionSheet({
                itemList,
                itemColor,
                success: resolve,
                fail: reject
            })
        })
    },
    //删除弹窗
    delModal(){
        return new Promise((resolve, reject) => {
            toast.actionSheet(['删除']).then(({tapIndex}) =>{
                if(tapIndex === 0){
                    toast.modal().then(resolve).catch(reject)
                }else{
                    reject()
                }
            }).catch(reject)
        })
    }
}

/*头部bar设置*/
export const bar = {
    loading(){
        Taro.showNavigationBarLoading({})
    },
    hide(){
        Taro.hideNavigationBarLoading({})
    },
    title(title){
        Taro.setNavigationBarTitle({title})
    },
    color(bgColor, color){
        Taro.setNavigationBarColor({backgroundColor: bgColor, frontColor: color, animation: {duration: 200, timingFunc: 'easeIn'}})
    },
    hideHomeButton(){
        Taro.hideHomeButton()
    }
}

/*
* 全局消息事件
* */
const events = new Events()
export const bus = {
    $on(eventName, fn){
        events.on(eventName, fn);
    },
    $emit(eventName, ...arg){
        events.trigger(eventName, ...arg)
    }
}
/*
* 将对象转换成GET参数
* */
export function objToGetParams(obj){
    let arr = [];
    for(let key in obj){
        arr.push(`${key}=${obj[key]}`)
    }
    return arr.join('&')
}
/*
* 将GET参数转换成POST参数
* */
export function strToPostParams(str){
    if(!str)return str;
    let arr = str.split('&');
    let params = {};
    arr.forEach(item => {
        let s = item.split('=');
        params[s[0]] = s[1]
    })
    return params
}

/*
* router
* */
export const router = {
    push(url, params = {}, events = {}){
        return new Promise((resolve, reject) => {
            Taro.navigateTo({url: url + '?' + objToGetParams(params), fail: reject, success: resolve, events})
        })
    },
    goBack(){
        Taro.navigateBack({})
    },
    //跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
    switchTab(url){
        return new Promise((resolve, reject) => {
            Taro.switchTab({
                url,
                fail: reject,
                success: resolve
            })
        })
    },
    //关闭所有页面，打开到应用内的某个页面
    reLaunch(url){
        return new Promise((resolve, reject) => {
            Taro.reLaunch({
                url,
                fail: reject,
                success: resolve
            })
        })
    },
    //关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
    redirectTo(url){
        return new Promise((resolve, reject) => {
            Taro.redirectTo({
                url,
                fail: reject,
                success: resolve
            })
        })
    },
}

/*
* POST
* @params url
* @params params
* @return Promise
* */
export function post(url, params = {}){
    return request.post(url,  params)
}
/*
* GET
* @params url
* @params params
* @return Promise
* */
export function get(url, params = {}){
    return request.get(url, {params})
}

/*
* 上传文件
* @param url
* @param FileData
* */
export function upload(url, fileData){
    return post(url, new PostData({
        smfile: new FileData(fileData),
        ssl: true,
        format: 'json',
    }),)
}
/*
* 将 2020-06-06 转换 2020/06/06
* */
export function lineDateToSlash(date){
    if(typeof date === 'string' && date.indexOf('-')){
        return new Date(date.replaceAll('-', '/'))
    }
    return date;
}
/*
* 日期格式化
* */
export const format = {
    date(date, format = 'YYYY-MM-DD'){
        return moment(lineDateToSlash(date)).format(format);
    },
    time(date , format = 'HH:mm:ss'){
        return moment(lineDateToSlash(date)).format(format);
    },
    dateTime(date , format = 'YYYY-MM-DD HH:mm'){
        return moment(lineDateToSlash(date)).format(format);
    },
    obj(date){
        moment.locale('zh-cn')
        let d = moment(lineDateToSlash(date)).toObject();
        d.months += 1;
        return d;
    }
}

/*
* 取数组对象中的一个属性，并且拼接字符串
* @param list Array [{}]
* @param attr String 取的属性,默认 id
* @param bool Boolean 是否拼接,
* @param format String 拼接的格式， 默认是逗号
* */
export function getListAttr(list = [], attr = 'id', bool = false, format = ','){
    let arr = list.map(item => item[attr]);
    return bool ? arr.join(format) : arr;
}
